import {AfterViewInit, Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core';
import {Hotspot} from "../../models/hotspot";

@Component({
  selector: 'app-baidu-map',
  templateUrl: './baidu-map.component.html',
  styleUrls: ['./baidu-map.component.css']
})
export class BaiduMapComponent implements OnInit, AfterViewInit {
  url:string = 'http://api.map.baidu.com/api?v=2.0&ak=Bc4bqm4woP6gMOyoVOTAEIAp4Q48EeTb'

  constructor() { }

  @ViewChild('map')
  mapDiv: ElementRef;
  map: any;
  @Input() hotspots: Hotspot[]

  ngOnInit() {
  }
  loadJS(url){
    let script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    script.onerror = function() {
      document.body.removeChild(script);
    };
    document.body.appendChild(script);
  }
  getMap(){
    if(!this.map){
      var BMap = (<any>window)['BMap'];
      this.map = new BMap.Map(this.mapDiv.nativeElement);    // 创建Map实例
    }
    return this.map
  }
  ngAfterViewInit(){
    var BMap = (<any>window)['BMap'];
    var map = this.getMap()
    //map.centerAndZoom(new BMap.Point(120.19, 30.26), 15);  // 初始化地图,设置中心点坐标和地图级别
    map.addControl(new BMap.MapTypeControl());   //添加地图类型控件
    map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
    this.setHotspots(BMap, map)
    this.scaleToFit(BMap, map)
  }
  setHotspots(BMap, map){
    this.hotspots.forEach(function(item, index, array){
      var point = new BMap.Point(item.lng, item.lat);
      var marker = new BMap.Marker(point);  // 创建标注
      map.addOverlay(marker);              // 将标注添加到地图中
      var label = new BMap.Label(item.title,{offset:new BMap.Size(20,-10)});
      label.setStyle({
        color : "black",
        fontSize : "24px",
        height : "20px",
        lineHeight : "20px",
        fontFamily:"微软雅黑",
        border: "none",
        background: "transparent"
      })
      marker.setLabel(label);
      marker.addEventListener('click',function () {
        let span = map.getBounds().toSpan()
        let lngRatio=0.3 // change these two values to get suitable offsets
        let latRatio=0.3
        let newCenter = {
          lng: item.lng+span.lng*lngRatio,
          lat: item.lat-span.lat*latRatio,
        }
        map.panTo(new BMap.Point(newCenter.lng, newCenter.lat))
      })
    })
  }
  scaleToFit(BMap, map){
    var pointList = new Array<any>();
    this.hotspots.forEach(function(item, index, array){
      pointList.push(new BMap.Point(item.lng, item.lat))
    })
    var viewpoint = map.getViewport(pointList,{margins: [30, 20, 0, 20]})
    map.centerAndZoom(viewpoint.center,viewpoint.zoom)
  }
}
